//
//  MyMessageVc.swift
//  Venus
//
//  Created by apple on 2018/8/5.
//  Copyright © 2018年 zhaowang. All rights reserved.
//  我的消息

import UIKit
import SwiftyJSON
import MJRefresh

private let cellID = "MyMessageTableViewCellID"

class MyMessageVc: BaseViewController {
    fileprivate lazy var tableView : UITableView = {
        let tableView = UITableView(frame: CGRect.zero, style: .plain)
        tableView.showsVerticalScrollIndicator = false
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.register(MyMessageTableViewCell.self, forCellReuseIdentifier: cellID)
        tableView.estimatedRowHeight = 44.0
        tableView.rowHeight = UITableView.automaticDimension
        return tableView
    }()
    
    var cuttentPage:Int = 1
    
    var modelArr:[MyMessageModel] = [MyMessageModel]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        self.hudLoad()
        loadData()
    }
    
}


// MARK: - 协议
extension MyMessageVc:MyMessageTableViewCellDelegate , RefreshControl {
    
    func refreshingAction(refreshControl: MJRefreshNormalHeader) {
        refreshControl.beginRefreshing()
        loadData()
    }
    
    func refreshingActionFooter(refreshControl: MJRefreshAutoNormalFooter) {
        let dict = ["pageNo":self.cuttentPage,
                    "pageSize":10,
                    "type":"00"
            ] as [String : Any]
        
        
        TempNetTool.get(kHost + kqueryMsg + "".apiF(time: "1", sign: "1"), parameters: dict, progress: nil, success: { [weak self](result) in
            let modelA = MyMessageModel.formatModel(json: JSON(result!))
            if modelA.count < 10 {
                self?.tableView.mj_footer.endRefreshingWithNoMoreData()
            }else {
                self?.tableView.mj_footer.resetNoMoreData()
            }
            self?.cuttentPage = (self?.cuttentPage)! + 1
            self?.modelArr.append(contentsOf: modelA)
            self?.tableView.reloadData()
            self?.tableView.mj_footer.endRefreshing()
            
        }) { [weak self] (error) in
            self?.tableView.mj_footer.endRefreshing()
        }
    }
    
    func reloadHeight(index: IndexPath) {
        self.tableView.rectForRow(at: index)
    }
}


// MARK: - 网络请求 可以抽出 也可以不抽
extension MyMessageVc {
    @objc func networkError() {
        loadData()
    }
    
    func loadData() {
        let dict = ["pageNo":1,
                    "pageSize":10,
                    "type":"00"
            ] as [String : Any]
        
        self.modelArr.removeAll()
        TempNetTool.get(kHost + kqueryMsg + "".apiF(time: "1", sign: "1"), parameters: dict, progress: nil, success: { [weak self](result) in
            self?.hudHide()
            self?.tableView.mj_header.endRefreshing()
            self?.modelArr = MyMessageModel.formatModel(json: JSON(result!))
            self?.cuttentPage = 2
            self?.myShow()
            
        }) { [weak self] (error) in
            self?.tableView.reloadData()
            self?.tableView.mj_header.endRefreshing()
            self?.showNetworkErrorView(action: #selector(self?.networkError))
        }
    }
    
    func myShow() {
        if self.modelArr.count >= 0 {
            if self.modelArr.count < 10 {
                self.tableView.mj_footer.endRefreshingWithNoMoreData()
            }else {
                self.tableView.mj_footer.resetNoMoreData()
            }
            self.tableView.reloadData()
        }else {
            self.showInputEmptyView(tipTitle: "没有数据", imgName: "", toView: self.tableView)
        }
    }
}



// MARK: - UITableViewDelegate , UITableViewDataSource
extension MyMessageVc:UITableViewDelegate , UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.modelArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView .dequeueReusableCell(withIdentifier: cellID, for: indexPath)  as! MyMessageTableViewCell
        cell.delegate = self
        cell.configModel(modelArr: self.modelArr, index: indexPath)
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model:MyMessageModel = self.modelArr[indexPath.item]
        if model.msgType == 2 {
            self.hudLoadMessage("话题已被删除")
        }else if model.msgType == 1 {
            let vc = TopicDetailViewController()
            vc.modelID = model.msgId
            vc.loadModelData()
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return self.modelArr[indexPath.item].cellHeight
    }
}


// MARK: - 设置基础UI
extension MyMessageVc{
    
    func setupUI() {
        view.backgroundColor = UIColor.white
        self.view.bringSubviewToFront(self.navgationBar)
        self.title = "我的消息"
        
        view.addSubview(tableView)
        setupRefreshControl(scrollView: self.tableView, target: self)
        setupRefreshFootControl(scrollView:  self.tableView, target: self)
        tableView.snp.makeConstraints { (make) in
            make.left.right.equalTo(view)
            make.top.equalTo(LayoutCommon.navHeight)
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            } else {
                make.bottom.equalTo(view.snp.bottom)
            }
        }
    }
    
}
